package com.macro.mall.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.macro.mall.common.exception.ApiException;
import com.macro.mall.common.exception.Assert;
import com.macro.mall.mgb.mapper.*;
import com.macro.mall.mgb.model.*;
import com.macro.mall.portal.dao.PortalProductDao;
import com.macro.mall.portal.domain.PmsPortalProductDetail;
import com.macro.mall.portal.domain.PmsProductCategoryNode;
import com.macro.mall.portal.service.PortalProductService;
import com.macro.mall.portal.util.GenericConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author wangwang
 * @version 1.0
 * @description 前台商品管理
 * @date 2025/7/28 20:08
 */
@Service
public class PortalProductServiceImpl implements PortalProductService {

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private BrandMapper brandMapper;

    @Autowired
    private ProductAttributeMapper productAttributeMapper;

    @Autowired
    private ProductAttributeValueMapper productAttributeValueMapper;

    @Autowired
    private SkuStockMapper skuStockMapper;

    @Autowired
    private ProductLadderMapper productLadderMapper;

    @Autowired
    private ProductFullReductionMapper productFullReductionMapper;

    @Autowired
    private PortalProductDao productDao;


    @Override
    public List<PmsProductCategoryNode> categoryTreeList() {
        //获取所有分类
        List<ProductCategory> categoryList = productCategoryMapper.selectList(null);
        //转成需要的类型
        List<PmsProductCategoryNode> categoryDtos = GenericConverter.convertList(categoryList, PmsProductCategoryNode.class);
        //借助map存储结果，方便得到结果
        Map<Long, PmsProductCategoryNode> categoryMap = categoryDtos.stream().collect(Collectors.toMap(PmsProductCategoryNode::getId, Function.identity()));

        //构建树形结构
        List<PmsProductCategoryNode> roots = new ArrayList<>();
        categoryDtos.forEach(item -> {
            if (item.getParentId() == 0) {
                roots.add(item);
            } else {
                //获取父节点
                PmsProductCategoryNode parent = categoryMap.get(item.getParentId());
                if (parent != null) {
                    //如果子节点不存在
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(item);
                }
            }
        });
        return roots;
    }

    @Override
    public PmsPortalProductDetail detail(Long productId) {
        //1.获取商品信息
        Product product = productMapper.selectById(productId);
        if (product == null) {
            Assert.fail("商品不存在");
        }
        //2.获取商品品牌
        Brand brand = brandMapper.selectById(product.getBrandId());
        //3.获取商品属性和参数
        //根据属性分类id获取商品的属性
        LambdaQueryWrapper<ProductAttribute> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductAttribute::getProductAttributeCategoryId, product.getProductAttributeCategoryId());
        List<ProductAttribute> productAttributeList = productAttributeMapper.selectList(wrapper);
        //4.获取手动录入的商品属性与参数值
        List<ProductAttributeValue> productAttributeValueList = null;
        if (!productAttributeList.isEmpty()) {
            //商品属性的所有id
            List<Long> ids = productAttributeList.stream().map(ProductAttribute::getId).collect(Collectors.toList());
            LambdaQueryWrapper<ProductAttributeValue> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(ProductAttributeValue::getProductId, productId).in(ProductAttributeValue::getProductAttributeId, ids);
            productAttributeValueList = productAttributeValueMapper.selectList(wrapper1);
        }
        //5.获取商品的sku库存信息
        LambdaQueryWrapper<SkuStock> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(SkuStock::getProductId, productId);
        List<SkuStock> skuStockList = skuStockMapper.selectList(wrapper2);
        //6.获取商品阶梯价格设置
        List<ProductLadder> productLadderList = null;
        if (product.getPromotionType() == 3) {
            LambdaQueryWrapper<ProductLadder> wrapper3 = new LambdaQueryWrapper<>();
            wrapper3.eq(ProductLadder::getProductId, productId);
            productLadderList = productLadderMapper.selectList(wrapper3);
        }
        //7.获取商品满减价格设置
        List<ProductFullReduction> productFullReductionList = null;
        if (product.getPromotionType() == 4) {
            LambdaQueryWrapper<ProductFullReduction> wrapper4 = new LambdaQueryWrapper<>();
            wrapper4.eq(ProductFullReduction::getProductId, productId);
            productFullReductionList = productFullReductionMapper.selectList(wrapper4);
        }
        //8.获取商品可用优惠券
        //商品可用优惠券
        List<SmsCoupon> couponList = productDao.getAvailableCouponList(product.getId(), product.getProductCategoryId());

        return PmsPortalProductDetail.builder()
                .product(product)
                .brand(brand)
                .productAttributeList(productAttributeList)
                .productAttributeValueList(productAttributeValueList)
                .skuStockList(skuStockList)
                .productLadderList(productLadderList)
                .productFullReductionList(productFullReductionList)
                .couponList(couponList)
                .build();
    }

    @Override
    public List<Product> search(String keyword, Long brandId, Long productCategoryId, Integer pageNum, Integer pageSize, Integer sort) {
        Page<Product> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getPublishStatus, 1)
                .eq(Product::getDeleteStatus, 0);
        if (StrUtil.isNotEmpty(keyword)) {
            wrapper.like(Product::getKeywords, keyword);
        }
        if (brandId != null) {
            wrapper.eq(Product::getBrandId, brandId);
        }
        if (productCategoryId != null) {
            wrapper.eq(Product::getProductCategoryId, productCategoryId);
        }
        //1->按新品；2->按销量；3->价格从低到高；4->价格从高到低
        switch (sort) {
            case 1: {
                wrapper.orderByDesc(Product::getId);
                break;
            }
            case 2: {
                wrapper.orderByDesc(Product::getSale);
                break;
            }
            case 3: {
                wrapper.orderByAsc(Product::getPrice);
                break;
            }
            case 4: {
                wrapper.orderByDesc(Product::getPrice);
            }
        }
        Page<Product> productPage = productMapper.selectPage(page, wrapper);
        return productPage.getRecords();
    }
}
